/**
 * Created by admin on 2017/9/12.
 */
define([
    "helpers/network",
    "helpers/util",
    "models/orders",
    "models/logistic",
    "views/modules/popup",
    "views/modules/form",
    "views/modules/table",
    "views/modules/pager"
], function (Network, Util, OrdersModel, LogisticModel, PopupView, CommonForm, CommonTable, CommonPager) {

    var id = "";
    var tableId = id + "table";
    var windowId = id + "window";
    var keywordsId = id + "keywordsId";
    var formId = id + "form";
    var queryPrerequisiteId = id + "queryPrerequisiteId";
    var searchFormId = id + "searchForm";
    var TYPE = "Order";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var pageIndex = 1, pageCounts;

    var onTableReady = function (page) {
        page = page || 1;
        var searchForm = $$(searchFormId).getValues();
        var obj = {
            params: {
                statuses: ["Paid"],
                // returnStatuses: ["ReturnApplied", "ReturnApproved", "ReturnRejected", "Returned", "Refunded"]
            },
            size: 20,
            page: page || 1,
            sort: ["creationTime,desc"]
        };

        // if (searchForm[keywordsId]) {
        //     if (searchForm[queryPrerequisiteId] === "orderNo") {
        //         obj.params.data.no = searchForm[keywordsId];
        //     }
        //     if (searchForm[queryPrerequisiteId] === "userId" && Number(searchForm[keywordsId])) {
        //         obj.params.data.userSnapshot = {id: Number(searchForm[keywordsId])};
        //     }
        //     if (searchForm[queryPrerequisiteId] === "goodsName") {
        //         obj.params.goodsSnapshot = {name: searchForm[keywordsId]};
        //     }
        // }
        Network.ajax("/PointsGoodsOrderView.queryAll.query", obj, function (ret) {
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        });
        pageIndex = page ? page : 1
    };

    var closeWindow = function () {
        if ($$(windowId)) {
            $$(windowId).close();
        }
    };

    var ShowOrderDetailWindow = function (title, item) {
        PopupView(windowId, title, {
            view: "scrollview", scroll: "y",
            body: {
                rows: [
                    {
                        view: "property", id: "sets", autoheight: true,
                        elements: [
                            {label: "收货信息", type: "label"},
                            {label: "用户ID", value: item.userId},
                            {label: "姓名", value: item.userSnapshot.nickname},
                            {label: "联系电话", value: item.userSnapshot.mobile},
                            // {label: "收货地址", value: OrdersModel.getShippingAddress(item)},
                            {label: "收货地址", value: item.shippingInfo},

                            {label: "商品信息", type: "label"},
                            // {label: "编号", value: item.goodsSnapshot.no},
                            {label: "名称", value: item.pointsGoodsSnapshot.name},
                            // {label: "名称", value: OrdersModel.getNameWithTags(item)},
                            // {label: "属性", value: JSON.stringify(item.data.spec)},

                            // {label: "供应商信息", type: "label"},
                            // {label: "名称", value: item.goodsSellerSnapshot.name || "无"}

                        ]
                    },
                    {
                        view: "form", borderless: true, id: "3rdOrderForm",
                        // rules: {$all: webix.rules.isNotEmpty},
                        elements: [
                            {
                                id: "expressName",
                                view: "combo", label: "物流", name: "expressName",
                                placeholder: "请选择物流", required: true,
                                options: {
                                    data: LogisticModel.data,
                                    filter: function (item, value) {
                                        return item.value.toString().toLowerCase().indexOf(value.toLowerCase()) !== -1
                                    }
                                }
                            },
                            {
                                id: "expressNo", name: "expressNo", view: "text", label: "快递单号", required: true
                            },
                            {
                                id: "expressMemo", name: "expressMemo", view: "text", label: "备注"
                            },
                            {
                                view: "button", label: "确认",
                                click: function () {
                                    if (!this.getParentView().validate()) {
                                        webix.message({type: "warn", text: "信息输入不完整"});
                                        return
                                    }

                                    var formVal = $$("3rdOrderForm").getValues();
                                    var obj = {
                                            data: {
                                                id: item.id,
                                                sentInfo: {
                                                    expressName: formVal.expressName,
                                                    expressNo: formVal.expressNo,
                                                    expressMemo: formVal.expressMemo,
                                                    expressTime: Date.parse(new Date())
                                                }
                                            }
                                    };

                                    Network.ajax("/PointsGoodsOrderTransactor.sent.command", obj, function (ret) {
                                        closeWindow();
                                        $$(tableId).remove(item.id);
                                        webix.message("操作成功...")
                                        // onTableReady();
                                    })
                                }
                            }]
                    }
                ]
            }
        }, 500, 580)
    };

    var genSearchFormUI = function () {
        return {
            id: searchFormId, view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
            cols: [
                {},
                {
                    id: queryPrerequisiteId,
                    name: "queryPrerequisiteId",
                    view: "select",
                    width: 100,
                    css: {"text-align": "center"},
                    value: "orderNo",
                    options: [
                        {id: "orderNo", value: "订单号"},
                        {id: "userId", value: "用户ID"},
                        {id: "goodsName", value: "商品名称"},
                    ]
                },
                CommonForm.genKeywordsUI(keywordsId, "依据左边状态查询", onTableReady),
                CommonForm.genQueryButtonUI(onTableReady)
            ]
        }
    };

    var genOperationFormUI = function () {
        return {
            view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
            cols: [
                {view: "label", label: "操作"},
                {
                    view: "button", label: "导出文件", width: 90, disabled: true,
                    click: function () {
                        // getExportData()
                    }
                },
                {
                    view: "button", label: "填物流", width: 90,
                    // hidden: Authority.hasNoAuth("GOODS_ADD"),
                    click: function () {
                        var item = $$(tableId).getSelectedItem();
                        if (!item) return;
                        ShowOrderDetailWindow("填物流", item)
                    }
                }
            ]
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row", data: [],
            ready: onTableReady,
            columns: [
                {
                    id: "no",
                    header: {text: "订单号", css: {"text-align": "center"}},
                    css: {"text-align": "center"}, width: 200,
                },
                {
                    id: "goodsName",
                    header: {text: "(ID)商品名称", css: {"text-align": "center"}},
                    css: {"text-align": "center"}, fillspace: true,
                    template: "#pointsGoodsSnapshot.name#"
                },
                {
                    id: "userId",
                    header: {text: "用户ID", css: {"text-align": "center"}},
                    css: {"text-align": "center"},
                },
                {
                    id: "count",
                    header: {text: "数量", css: {"text-align": "center"}},
                    css: {"text-align": "center"},
                    template: OrdersModel.getBuyingCountWithColor
                },
                {
                    id: "paidTime",
                    header: {text: "用户支付时间", css: {"text-align": "center"}},
                    css: {"text-align": "center"}, width: 140,
                    template: function (obj) {
                        if (!obj.paidTime) return "";
                        return Util.getFormattedDateTime("yyyy-MM-dd hh:mm:ss", new Date(obj.paidTime))
                    }
                }
            ],
            on: {
                onItemClick: function () {
                    // $$("btnPass").enable();
                    // $$("btnRejec").enable();
                },
                onItemDblClick: function (id) {
                    // if (Authority.hasNoAuth("SHOPPINGGOLD_ORDERS_LOGISTIC_INFO_ADD")) {
                    //     return
                    // }
                    // showPopupWindow("物流卡", this.getItem(id))
                }
            }
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            padding: 10,
            rows: [
                genSearchFormUI(),
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };

});